package com.fsd.admin.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.ParametersUtil;
import com.fsd.core.wechat.entity.message.resp.TemplateMessage;
import com.fsd.core.wechat.util.WeixinUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_article;
import com.fsd.admin.model.E_userinfo;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.B_articleService;
import com.fsd.admin.service.E_WechatService;
import com.fsd.admin.service.E_pushtemplatesService;
import com.fsd.admin.service.E_userinfoService;
import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.admin.dao.E_UserinfoDao;

@Repository("e_userinfoServiceImpl")
public class E_userinfoServiceImpl extends MainServiceImpl<E_userinfo, String> implements E_userinfoService{
    
    private static final Logger log = Logger.getLogger(E_userinfoServiceImpl.class);
    private String depict = "微信用户：";
    
    private static final Lock lock = new ReentrantLock();
    
    @Resource(name = "e_userinfoDaoImpl")
	public void setBaseDao(E_UserinfoDao E_userinfoDao) {
		super.setBaseDao(E_userinfoDao);
	}
	
	@Resource(name = "e_userinfoDaoImpl")
	private E_UserinfoDao objectDao;
	
	//用户
    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
	
    //微信推送模板
    @Resource(name = "e_pushtemplatesServiceImpl")
	private E_pushtemplatesService pushtemplatesService;
    
	@Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParamService;
    
	@Resource(name = "e_wechatServiceImpl")
	private E_WechatService wechatService;
	
	@Autowired
	private B_articleService articleService;
	
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		// c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.asc("adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("realname") != null && !"".equals(objectMap.get("realname"))){
				c.add(Restrictions.like("realname", "%" + objectMap.get("realname") + "%"));
			}
			if(objectMap.get("nickname") != null && !"".equals(objectMap.get("nickname"))){
				c.add(Restrictions.like("nickname", "%" + objectMap.get("nickname") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	public void save(E_userinfo obj, A_Employee employee) throws Exception{
		Long num = 0l;
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            E_userinfo old_obj = objectDao.get(obj.getId());
            if(!obj.getOpenid().equals(old_obj.getOpenid())){
				num = objectDao.getCount("openid = '" + obj.getOpenid() + "'");
				if (num > 0){
					throw new BusinessException(depict + "OpenID已存在!");
				}
			}
            old_obj.setEmployeeid(obj.getEmployeeid());
            old_obj.setRealname(obj.getRealname());
            old_obj.setOpenid(obj.getOpenid());
            old_obj.setNickname(obj.getNickname());
            old_obj.setSex(obj.getSex());
            old_obj.setLanguage(obj.getLanguage());
            old_obj.setCity(obj.getCity());
            old_obj.setProvince(obj.getProvince());
            old_obj.setCountry(obj.getCountry());
            old_obj.setHeadimgurl(obj.getHeadimgurl());
            objectDao.update(old_obj);
        }else{
            //添加
        	num = objectDao.getCount("openid = '" + obj.getOpenid() + "'");
			if (num > 0){
				throw new BusinessException(depict + "OpenID已存在!");
			}
            obj.setId(this.getUUID());//设置主键
			obj.setCompanyid(employee.getCompanyid());//所属单位
			obj.setAdddate(this.getData());
			objectDao.save(obj);
        }
        this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getNickname(), employee, E_userinfoServiceImpl.class);
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
		}
		String hql = "";
		objectDao.executeHql("delete from E_userinfo where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPESC, this.depict + ids, employee, E_userinfoServiceImpl.class);
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_userinfo getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null || "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_userinfo obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
    
    /**
	 * 根据EmployeeID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public E_userinfo getObjectByEmployeeId(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("employeeid") == null || "".equals(objectMap.get("employeeid"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("employeeid", objectMap.get("employeeid").toString()));
		List<E_userinfo> objList = objectDao.getList(c);
		if(objList == null || objList.size() == 0){
			throw new BusinessException(depict + "数据不存在!");
		}
		return objList.get(0);
	}
	
	/**
	 * 根据用户ID加载绑定的微信信息
	 * @param employeeId
	 * @return
	 * @throws Exception
	 */
	public E_userinfo getObjectByEmployeeId(String employeeId) throws Exception{
		String sql = "select * from e_userinfo where employeeid = ?";
		List<E_userinfo> list = objectDao.queryBySql1(sql, employeeId);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 根据openid加载绑定微信列表
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	public E_userinfo getObjectByOpenId(String openid) throws Exception{
		String sql = "select * from e_userinfo where openid = ?";
		List<E_userinfo> list = objectDao.queryBySql1(sql, openid);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	/**
	 * 根据微信openid 添加微信用户信息
	 * @param wechat 系统微信配置
	 * @param openid 微信用户openid
	 * @return
	 * @throws Exception
	 */
	public E_userinfo saveObject(E_wechat wechat, String openid) throws Exception{
		E_userinfo userinfo = this.getObjectByOpenId(openid);
		if(userinfo == null) {
			userinfo = new E_userinfo();
			userinfo.setId(this.getUUID());
			userinfo.setOpenid(openid);
			userinfo.setAdddate(this.getData());
		}
		Map<String, Object> map = WeixinUtil.getUserInfo(wechat.getAppid(), wechat.getAppsecret(), openid);
		if(map != null){
			userinfo.setNickname(map.get("nickname").toString());
			if("0".equals(map.get("sex"))) {
				userinfo.setSex("未知");
			}else if("1".equals(map.get("sex"))) {
				userinfo.setSex("男");
			}else if("2".equals(map.get("sex"))) {
				userinfo.setSex("女");
			}
			userinfo.setLanguage(map.get("language").toString());
			userinfo.setCountry(map.get("country").toString());
			userinfo.setProvince(map.get("province").toString());
			userinfo.setCity(map.get("city").toString());
			userinfo.setHeadimgurl(map.get("headimgurl").toString());
		}
		objectDao.save(userinfo);
		return userinfo;
	}
	
	/**
	 * 修改人员信息子类重写方法
	 */
	public void updateAEmployeeInfo(String objSimpleName, Object object) throws Exception{
		A_Employee employee = (A_Employee)object;
		E_userinfo userinfo = this.getObjectByEmployeeId(employee.getId());
		if (userinfo != null){
			userinfo.setRealname(employee.getRealname());
			objectDao.update(userinfo);
		}
	}
	
	/**
	 * 获得用户绑定二维码
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public String getWechatQRcode(ParametersUtil param) throws Exception {
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("id") == null || "".equals(objectMap.get("id"))){
				throw new BusinessException(depict + "用户微信绑定，用户编号不得为空！");
			}
			String id = objectMap.get("id").toString();
			E_userinfo userinfo = this.getObjectByEmployeeId(id);
			if(userinfo != null) {
				throw new BusinessException(depict + "用户微信已绑定，如要执行该操作，请先解除绑定！");
			}
			A_Employee employee = employeeService.get(id);
			if(employee == null) {
				throw new BusinessException(depict + "用户微信绑定，用户数据不存在！" + id);
			}
			if(null != employee.getIswechatbind() && "true".equals(employee.getIswechatbind())) {
				throw new BusinessException(depict + "用户微信已绑定，如要执行该操作，请先解除绑定！");
			}
			String wechatApiId = sysParamService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
			E_wechat wechat = wechatService.getObjectByApiId(wechatApiId);
			return WeixinUtil.getTemporaryQRcode(wechat.getAppid(), wechat.getAppsecret(), 300, E_wechatCoreService.scanQRcodeBind + id);
		}else {
			throw new BusinessException(depict + "用户微信绑定, 未找到参数信息！");
		}
	}

	/**
	 * 扫码根据参数绑定用户
	 * @param wechat
	 * @param openid
	 * @param employeeid
	 * @return
	 * @throws Exception
	 */
	public String saveUserInfoBindByQRcode(E_wechat wechat, String openid, String employeeid) throws Exception {
		if(openid == null || "".equals(openid)){
			return "系统错误，请联系管理员！";
		}
		if(employeeid == null || "".equals(employeeid)){
			return "系统错误，请联系管理员！";
		}
		E_userinfo userinfo = this.getObjectByOpenId(openid);
		if(userinfo != null){
			return "该微信账号已绑定用户，如有疑问请联系管理员！";
		}
		E_userinfo userbind = this.getObjectByEmployeeId(employeeid);
		if(userbind != null){
			return "该用户已绑定微信账号，如有疑问请联系管理员！";
		}
		A_Employee employee = this.employeeService.get(employeeid);
		if(employee == null){
			return "您扫描绑定的用户，无法找到用户信息。请联系管理员核实！";
		}
		userinfo = new E_userinfo();
		userinfo.setId(this.getUUID());
		userinfo.setOpenid(openid);
		userinfo.setAdddate(this.getData());
		userinfo.setEmployeeid(employeeid);
		userinfo.setRealname(employee.getRealname());
		Map<String, Object> map = WeixinUtil.getUserInfo(wechat.getAppid(), wechat.getAppsecret(), openid);
		if(map != null){
			userinfo.setNickname(map.get("nickname").toString());
			if("0".equals(map.get("sex"))) {
				userinfo.setSex("未知");
			}else if("1".equals(map.get("sex"))) {
				userinfo.setSex("男");
			}else if("2".equals(map.get("sex"))) {
				userinfo.setSex("女");
			}
			userinfo.setLanguage(map.get("language").toString());
			userinfo.setCountry(map.get("country").toString());
			userinfo.setProvince(map.get("province").toString());
			userinfo.setCity(map.get("city").toString());
			userinfo.setHeadimgurl(map.get("headimgurl").toString());
		}
		this.objectDao.save(userinfo);
		employee.setIswechatbind("true");
		employee.setIswechatpush("true");
		this.employeeService.update(employee);
		return "绑定成功";
	}

	/**
	 * 删除微信绑定
	 * @param employee 用户编号
	 * @return
	 * @throws Exception
	 */
	public void delUserInfoBind(ParametersUtil param, A_Employee employee) throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		if(objectMap.get("id") == null || "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_userinfo obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
        this.employeeService.delWechatBind(obj.getEmployeeid());
		obj.setEmployeeid("");
        objectDao.update(obj);
        this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getNickname() + "解除微信绑定", 
        		employee, E_userinfoServiceImpl.class);
	}
	
	/**
	 * 为用户推送消息
	 * @param parameters
	 */
	public void pushArticleinfoToUserinfo(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> articleIds = (ArrayList<String>) objectMap.get("ids");
		
		String id = objectMap.get("id").toString();
		
		A_Employee employee = employeeService.get(id);
		if (employee == null) {
			throw new BusinessException("会员用户不存在");
		}
		
		String wechatApiId = sysParamService.getParameterValueByCode(Sys_SystemParametersServiceImpl.WECHATMEMBER, employee.getCompanyid());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		for(int i = 0; i<articleIds.size(); i++) {
			B_article article = articleService.get(articleIds.get(i));
			TemplateMessage message = new TemplateMessage();
			message.setItem("first", "尊敬的：" + employee.getRealname(), "#000000");
			message.setItem("keyword1", article.getTitle(), "#000000");
			message.setItem("keyword2", format.format(new Date()), "#000000");
			message.setItem("remark", "详细内容请点击详情查看，如有疑问，请致电0931-4100411联系我们。", "#1111EE");
			message.setUrl("http://192.168.31.122/fsdsitegroup/wap/content-" + articleIds.get(i) + ".htm");
			pushtemplatesService.sendTemplateMessage(wechatApiId, E_pushtemplatesServiceImpl.pushHYcz, employee, message);
		}
	}
		
}
